package uy.com.csi.gestpro.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRXlsExporter;

public class Reporte {
	public static final int FORMAT_PDF;
	public static final int FORMAT_EXCEL;

	static {
		FORMAT_PDF = 0;
		FORMAT_EXCEL = 1;
	}

	@SuppressWarnings({  "hiding" })
	public void generarReporte(Map<String, Object> pm, String rutaReporte, String fileGeneration, int exportFormat) {
		JasperPrint jp = null;
		try {

			if (PostgresConectorJdbc.conectar()) {
				try {
					if (exportFormat == FORMAT_PDF) {
						File f = new File(rutaReporte);
						InputStream reportSt = new BufferedInputStream(new FileInputStream(f));
						jp = JasperFillManager.fillReport(reportSt, pm, PostgresConectorJdbc.getConexion());
						OutputStream output = new FileOutputStream(new File(fileGeneration));
						JasperExportManager.exportReportToPdfStream(jp, output);
						reportSt.close();
						output.close();
					} else if (exportFormat == FORMAT_EXCEL) {
						JRXlsExporter exporter = new JRXlsExporter();
						String printFileName = JasperFillManager.fillReportToFile(rutaReporte, pm, PostgresConectorJdbc.getConexion());
						exporter.setParameter(JRExporterParameter.INPUT_FILE_NAME, printFileName);
						exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, fileGeneration);
						exporter.exportReport();
					}

				} catch (JRException ex) {
					ex.printStackTrace();
				} catch (FileNotFoundException ex) {
					Logger.getLogger(Reporte.class.getName()).log(Level.SEVERE, null, ex);
				} catch (IOException ex) {
					Logger.getLogger(Reporte.class.getName()).log(Level.SEVERE, null, ex);
				} finally {
					PostgresConectorJdbc.cerrarConexion();
				}
			}
		} catch (ClassNotFoundException ex) {
			Logger.getLogger(Reporte.class.getName()).log(Level.SEVERE, null, ex);
		} catch (SQLException ex) {
			Logger.getLogger(Reporte.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

}
